package com.bed.lovewithpatientbed.controller;

import com.bed.lovewithpatientbed.common.bean.LayUiPageBean;
import com.bed.lovewithpatientbed.common.bean.OrderDetailBean;
import com.bed.lovewithpatientbed.common.bean.UserOrderDetailBean;
import com.bed.lovewithpatientbed.common.params.OrderSearchParams;
import com.bed.lovewithpatientbed.pojo.*;
import com.bed.lovewithpatientbed.service.DeptService;
import com.bed.lovewithpatientbed.service.IOrderService;
import com.bed.lovewithpatientbed.service.IUserService;
import com.bed.lovewithpatientbed.util.DateUtil;
import com.bed.lovewithpatientbed.util.LayUiUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @author xuxiaoding
 * @version 1.0.0
 * @ClassName OrderController.java
 * @Description 订单管理Controller
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    private IOrderService orderService;

    private DeptService deptService;

    private IUserService userService;

    @Autowired
    public void setOrderService(IOrderService orderService) {
        this.orderService = orderService;
    }

    @Autowired
    public void setDeptService(DeptService deptService) {
        this.deptService = deptService;
    }

    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @GetMapping("/placeOrder")
    @ResponseBody
    public Map<String, Object> placeOrder(Order order) {
        Map<String, Object> responseMap = new HashMap<>();
        if (order == null ) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "传递参数为空");
            return responseMap;
        }

        if (order.getBedId() == null || order.getBedId() < 1) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "该床位不存在");
            return responseMap;
        }

        if (order.getOrderTypeId() == null || order.getOrderTypeId() < 1) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "未选择订单类型");
            return responseMap;
        }

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user == null) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "未登陆");
            return responseMap;
        }
        // 设置 userId
        order.setUserId(user.getUserId());

        boolean result = orderService.createOrder(order);
        responseMap.put("result", result);

        return responseMap;
    }

    /**
     * @title getOrderTypeList
     * @description 获取 OrderType 列表
     * @author xuxiaoding
     * @return 返回查询结果
     */
    @GetMapping("/getOrderTypeList")
    @ResponseBody
    public List<OrderType> getOrderTypeList() {
        return orderService.retrieveAllOrderType();
    }

    /**
     * @title getOrderListByUserId
     * @description 根据 userId 获取该用户所有订单，因为名字起的较为复杂，所以请求和方法名并没有对应
     * @author xuxiaoding
     * @param userId
     * @return
     */
    @GetMapping("/userOrder")
    @ResponseBody
    public Map<String, Object> getOrderListByUserId(Integer userId) {
        System.out.println("OrderController.getOrderListByUserId - userId = " + userId);
        Map<String, Object> responseMap = new HashMap<>();

        if (userId == null || userId < 1) {
            responseMap.put("msg", "Parameter Error");
            return responseMap;
        }

        // 查询
        List<Order> orderList = orderService.retrieveOrderByUserId(userId);

        if (orderList == null) {
            responseMap.put("msg", "Retrieve Failed");
            return responseMap;
        }

        /*
        Order转UserOrderDetailBean
         */
        List<UserOrderDetailBean> userOrderDetailBeanList = new ArrayList<>();
        for (Order order : orderList) {
            UserOrderDetailBean userOrderDetailBean = new UserOrderDetailBean();
            userOrderDetailBean.setOrderId(order.getOrderId());
            // 医院
            Hospital hospital = order.getHospital();
            // 添加医院名字
            userOrderDetailBean.setHospitalName(hospital.getHospitalName());
            // 查询科室
            List<Dept> deptList = deptService.getAll();
            if (deptList != null) {
                for (Dept dept : deptList) {
                    if (dept.getDeptId().equals(order.getDeptId())) {
                        // 添加科室名字
                        userOrderDetailBean.setDeptName(dept.getDeptName());
                    }
                }
            }
            userOrderDetailBean.setOrderPay(order.getOrderPay());
            userOrderDetailBean.setOrderStartTime(order.getOrderStartTime());
            userOrderDetailBean.setOrderUseTime(order.getOrderUseTime());
            userOrderDetailBeanList.add(userOrderDetailBean);
        }

        // 组装responseMap
        responseMap = LayUiUtil.getLayTableResponseMap("success", 0,
                userOrderDetailBeanList.size(), userOrderDetailBeanList);
        System.out.println(userOrderDetailBeanList);

        return responseMap;
    }

    /**
     * @title getOrderByConditionWithLimit
     * @description 根据条件分页查询订单信息
     * @author xuxiaoding
     * @param pageBean 分页信息
     * @param orderSearchParams 查询条件
     * @return
     */
    // @RequiresRoles("admin")
    @GetMapping("/getOrder")
    @ResponseBody
    public Map<String, Object> getOrderByConditionWithLimit(LayUiPageBean pageBean, OrderSearchParams orderSearchParams) {
        System.out.println("OrderController.getOrderByConditionWithLimit");
        System.out.println(pageBean);
        System.out.println(orderSearchParams);

        // 按条件查询总数
        long count = orderService.getCountByCondition(orderSearchParams);

        // 按条件分页查询
        List<Order> orderList = orderService.retrieveOrderByConditionWithLimit(pageBean, orderSearchParams);

        /*
        封装 OrderDetailBean
         */
        List<OrderDetailBean> orderDetailBeanList = new ArrayList<>();
        for (Order order : orderList) {
            OrderDetailBean orderDetailBean = new OrderDetailBean();
            orderDetailBean.setOrderId(order.getOrderId());
            orderDetailBean.setHospitalName(order.getHospital().getHospitalName());
            Dept dept = deptService.selectById(order.getDeptId());
            if (dept != null) {
                orderDetailBean.setDeptName(dept.getDeptName());
            }
            orderDetailBean.setBedId(order.getBedId());
            orderDetailBean.setOrderPay(order.getOrderPay());
            User user = userService.retrieveUserById(order.getUserId());
            if (user != null) {
                orderDetailBean.setUserPhone(user.getUserPhone());
            }
            // 计算订单结束时间
            Date orderEndDate = DateUtil.getEndDateAddHour(order.getOrderStartTime(), order.getOrderUseTime());
            // 如果订单结束时间在当前时间之前，即订单已经结束则显示租赁时长
            if (orderEndDate.before(DateUtil.getCurrentDate())) {
                orderDetailBean.setOrderUseTime(order.getOrderUseTime());
            }
            // 下单时间
            orderDetailBean.setOrderStartTime(order.getOrderStartTime());
            orderDetailBeanList.add(orderDetailBean);
        }

        return LayUiUtil.getLayTableResponseMap("success", 0,
                orderDetailBeanList.size(), orderDetailBeanList);
    }

    @GetMapping("/getSelectionHospitalInfo")
    @ResponseBody
    public List<Hospital> getHospitalSectionInfo() {
        System.out.println("OrderController.getHospitalSectionInfo");
        return orderService.retrieveAllHospital();
    }

    @GetMapping("/getSelectionDeptInfo")
    @ResponseBody
    public List<Dept> getSelectionDeptInfoByHospital(Integer hospitalId) {
        System.out.println("OrderController.getSelectionDeptInfoByHospital - hospitalId: " + hospitalId);
        if (hospitalId == null) {
            return null;
        }

        return orderService.retrieveDeptListByHospitalId(hospitalId);
    }

}
